
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <fcntl.h>
#include <unistd.h>

#include "random.h"

#define GET_RANDOM(__p)					({ \
											if(NULL != (__p)) \
											{ \
												*(__p) = (typeof(*(__p)))Lib_Random::getRandomU64(); \
												return true; \
											} \
											return false; \
										})

#ifdef __cplusplus

Lib_Random::Lib_Random(void)
{
}

Lib_Random::~Lib_Random(void)
{
}

bool Lib_Random::getRandom(void *value, unsigned int size)
{
	bool ret = false;

	int fd = -1;

	if(NULL != value && 0 < size)
	{
		fd = open("/dev/urandom", O_RDONLY);

		if(0 <= fd)
		{
			do
			{
				memset(value, 0, size);

				read(fd, value, size);

				for(unsigned int i = 0; size > i; i++)
				{
					if(0 != ((char *)value)[i])
					{
						ret = true;

						break;
					}
				}
			} while(true != ret);

			close(fd);
			fd = -1;
		}
	}

	return ret;
}

bool Lib_Random::getRandom(char *value, unsigned int size)
{
	return Lib_Random::getRandom((void *)value, size);
}

bool Lib_Random::getRandom(unsigned char *value, unsigned int size)
{
	return Lib_Random::getRandom((void *)value, size);
}

bool Lib_Random::getRandom(char *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(char));
}

bool Lib_Random::getRandom(unsigned char *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(unsigned char));
}

bool Lib_Random::getRandom(short *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(short));
}

bool Lib_Random::getRandom(unsigned short *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(unsigned short));
}

bool Lib_Random::getRandom(int *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(int));
}

bool Lib_Random::getRandom(unsigned int *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(unsigned int));
}

bool Lib_Random::getRandom(long int *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(long int));
}

bool Lib_Random::getRandom(unsigned long int *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(unsigned long int));
}

bool Lib_Random::getRandom(long long int *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(long long int));
}

bool Lib_Random::getRandom(unsigned long long int *value)
{
	return Lib_Random::getRandom((void *)value, sizeof(unsigned long long int));
}

#endif
